package com.wsw.aitools.qwen;

import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversation;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationParam;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationResult;
import com.alibaba.dashscope.common.MultiModalMessage;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.exception.UploadFileException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.HashMap;

@Slf4j
@Service
public class QwenApi {
    
    public static final String apiKey = "sk-fb786a3bf07d4449bcf77b157f19e89a";
    public static final String modelName = "qwen-vl-max";
    
    public String askQwen(String prompt, String fileUrl){
        
        MultiModalConversation conv = new MultiModalConversation();
        MultiModalMessage userMessage = MultiModalMessage.builder().role(Role.USER.getValue())
                .content(Arrays.asList(
                        new HashMap<String, Object>() {
                            {
                                put("image", fileUrl);
                            }
                        },
                        new HashMap<String, Object>() {
                            {
                                put("text", prompt);
                            }
                        })).build();
        MultiModalConversationParam param = MultiModalConversationParam.builder()
                .apiKey(apiKey)
                .model(modelName)
                .message(userMessage)
                .build();
        // 请求开始时间
        Long startTime = System.currentTimeMillis();

        MultiModalConversationResult result = null;
        try {
            result = conv.call(param);
        } catch (NoApiKeyException e) {
            throw new RuntimeException(e);
        } catch (UploadFileException e) {
            throw new RuntimeException(e);
        }

        Integer inputTokens = result.getUsage().getInputTokens();
        Integer outputTokens = result.getUsage().getOutputTokens();
        
        log.info("inputTokens: {}, outputTokens: {}", inputTokens, outputTokens);
        // 请求结束时间
        Long endTime = System.currentTimeMillis();
        log.info("请求耗时：" + (endTime - startTime) + "ms");
        
        return result.getOutput().getChoices().get(0).getMessage().getContent().get(0).get("text").toString();
    }
    
    
}
